package alex.edu;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ComposeActivity extends Activity {

	private final String STATUS_SEND_SUCCESS = "Status Added";
	private final String STATUS_SEND_FAILED = "Invalid username/password";
	private String mail = "";
	private String password = "";
	private String status = "";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.post_layout);
		View view = this.findViewById(R.id.AbsoluteLayout01);
		view.setBackgroundColor(Color.BLUE);
		Button share = (Button) this.findViewById(R.id.share_button);
		share.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getStatusData();
			}
		});
	}

	private void getStatusData() {
		mail = ((EditText) this.findViewById(R.id.mail_editbox)).getText()
				.toString();
		password = ((EditText) this.findViewById(R.id.pass_editbox)).getText()
				.toString();
		status = ((EditText) this.findViewById(R.id.status_editbox)).getText()
				.toString();
		try {
			byte[] b = new byte[1000];
			int length = doPost(getString(R.string.status_post),
					toStatusParams()).read(b);
			String msg = null;
			if (length == 84) // the lenght in case of request failed
				msg = STATUS_SEND_FAILED;
			else
				msg = STATUS_SEND_SUCCESS;
			// appear process result in a Toast
			Context context = getApplicationContext();
			int duration = Toast.LENGTH_LONG;
			Toast.makeText(context, msg, duration).show();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private InputStream doPost(String urlString, String params)
			throws IOException {
		URL url = new URL(urlString);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		InputStream in = null;
		OutputStream out;
		byte[] buff;
		con.setRequestMethod("POST");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.connect();
		out = con.getOutputStream();
		buff = params.getBytes("UTF8");
		out.write(buff);
		out.flush();
		out.close();
		in = con.getInputStream();
		return in;
	}

	public String toStatusParams() {
		return "user[email]=" + mail + "&user[password]=" + password
				+ "&user[status]=" + status;
	}

}
